package com.bnlr.lrparking.appui.order.stages;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.approve.ApproveActivity;
import com.bnlr.lrparking.appui.paypwd.SetPayPasswordActivity;
import com.bnlr.lrparking.appui.sharevalue.recharge.SubmitSuccessActivity;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.RetentionMoneyAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.event.IsStallPayEvent;
import com.bnlr.lrparking.event.StallPaySucceeEvent;
import com.bnlr.lrparking.model.TopUpM;
import com.bnlr.lrparking.model.WantBuyBean;
import com.bnlr.lrparking.model.WxM;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.pwddialog.SecurityEditCompileListener;
import com.bnlr.lrparking.util.pwddialog.SecurityPasswordEditText;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 *
 * @author hp
 * @date 2017/11/22
 * 车位保留金
 */

public class RetentionMoneyActivity extends BaseActivity {

    private Unbinder unbinder;
    @BindView(R.id.id_retentionmoney)
    ImageView id_retentionmoney;
    @BindView(R.id.rely_retensy)
    RelativeLayout rely_retensy;
    @BindView(R.id.rely_retenwx)
    RelativeLayout rely_retenwx;
    @BindView(R.id.checkBox_retenwx)
    CheckedTextView checkBox_retenwx;
    @BindView(R.id.checkBox_retensy)
    CheckedTextView checkBox_retensy;
    @BindView(R.id.tv_retention_btn)
    TextView tv_retention_btn;
    @BindView(R.id.tv_offline_btn)
    TextView tvOfflineBtn;
    @BindView(R.id.share_num)
    TextView share_num;
    @BindView(R.id.retent_gridr_view)
    GridView gridr_view;
    @BindView(R.id.rely_isread)
    RelativeLayout rely_isread;
    @BindView(R.id.ed_rertention_peice)
    EditText ed_rertention_peice;
    @BindView(R.id.ed_pricename)
    EditText ed_pricename;
    @BindView(R.id.ed_pricephone)
    EditText ed_pricephone;
    @BindView(R.id.rely_grid)
    RelativeLayout rely_grid;
    @BindView(R.id.check_isread)
    CheckedTextView check_isread;
    @BindView(R.id.retainage_protocol)
    RelativeLayout retainage_protocol;//车位保留金协议
    @BindView(R.id.tv_explain)
    TextView tvRetentionRate;
    /**
     * 0是微信支付
     * 1是收益值支付
     */
    private int payType=0;
    /**
     * 0是没有阅读
     * 1是已经阅读
     */
    private int isRead=0;
    private RetentionMoneyAdapter adapter;
    private List<TopUpM.DataBean> list=new ArrayList<>();
    private int intNum[]={2000,5000,10000};
    private String price="";
    private String hasRealAuth;
    /**
     * 支付密码
     */
    String idHavapaypassword;
    private AlertDialog paydialog;
    SecurityPasswordEditText editSecurityCode;
    private WantBuyBean buyBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retentionmoney);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this);
        Intent intent = getIntent();
        buyBean = intent.getParcelableExtra("info_mation");
        initView();
    }

    private void initView(){
        tvRetentionRate.setText("1、"+LrConstant.RATE_VALUE+"贡献值=人民币1元");
        getPersonInfo();
        share_num.setText("(剩余"+AppConfig.getInstance().getString("incomevalue", "")+"收益值)");

        id_retentionmoney.setOnClickListener(this);
        rely_retensy.setOnClickListener(this);
        rely_retenwx.setOnClickListener(this);
        tv_retention_btn.setOnClickListener(this);
        rely_isread.setOnClickListener(this);
        retainage_protocol.setOnClickListener(this);
        ed_rertention_peice.setOnClickListener(this);
        ed_rertention_peice.addTextChangedListener(this);
        tvOfflineBtn.setOnClickListener(this);
        list.add(new TopUpM.DataBean(intNum[0]));
        list.add(new TopUpM.DataBean(intNum[1]));
        list.add(new TopUpM.DataBean(intNum[2]));
        adapter=new RetentionMoneyAdapter(RetentionMoneyActivity.this,list);
        gridr_view.setAdapter(adapter);
        gridr_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelectPosition(position);
                adapter.notifyDataSetChanged();
                price= String.valueOf(intNum[position]);
                ed_rertention_peice.setText(intNum[position]+"");
                ed_rertention_peice.setSelection(ed_rertention_peice.getText().length());
                if (payType==0) {
                    tv_retention_btn.setText("立即支付" + intNum[position] + "元");
                }else if (payType==1){
                    tv_retention_btn.setText("立即支付" + intNum[position]*LrConstant.RATE_VALUE + "收益值");
                }
                rely_grid.setVisibility(View.GONE);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCLose(StallPaySucceeEvent event) {
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        hasRealAuth = AppConfig.getInstance().getString("isRealNameAuth","");
        idHavapaypassword = AppConfig.getInstance().getString("paypassword", "");
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        if (s.length()>-1) {
            price = ed_rertention_peice.getText().toString();
            if (TextUtils.isEmpty(price)) {
                tv_retention_btn.setText("立即支付");
            } else {
                if (payType == 0) {
                    tv_retention_btn.setText("立即支付" + price + "元");
                } else {
                    tv_retention_btn.setText("立即支付" + (Integer.valueOf(price) * LrConstant.RATE_VALUE) + "收益值");
                }
            }

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.id_retentionmoney:
                setBackMessage();
                break;
            case R.id.rely_isread:
                if (isRead==0){
                    isRead=1;
                    check_isread.setChecked(false);

                }else if(isRead==1){
                    isRead=0;
                    check_isread.setChecked(true);
                }
                break;
            case R.id.retainage_protocol:
                Intent intent=new Intent(baseContext,WebActivity.class);
                intent.putExtra("tag",8);
                startActivity(intent);
                break;
            case R.id.rely_retenwx:
                payType=0;
                checkBox_retenwx.setChecked(false);
                checkBox_retensy.setChecked(true);
                if (!price.equals("")) {
                    tv_retention_btn.setText("立即支付" + price + "元");
                }
                break;
            case R.id.rely_retensy:
                payType=1;
                checkBox_retenwx.setChecked(true);
                checkBox_retensy.setChecked(false);
                if (!price.equals("")) {
                    tv_retention_btn.setText("立即支付" + (Integer.valueOf(price) * LrConstant.RATE_VALUE) + "收益值");
                }
                break;
            case R.id.tv_retention_btn:
                //实名认证的判断

                if (isRead==0){
                    ToastUtils.showShort("请先阅读车位保留金协议");
                }else if (isRead==1) {
                    if (payType == 0) {
                        if (!TextUtils.isEmpty(price)) {
                            payDingJin(1,"");
                        }else {
                            ToastUtils.showShort("请选择金额");
                        }
                    } else if (payType == 1) {
//                        if(!isAuth()) {
//                            return;
//                        }
                        if (idHavapaypassword.equals("1")) {
                            if (!TextUtils.isEmpty(price)) {
                                showPayDialog();
                            }else {
                                ToastUtils.showShort("请选择金额");
                            }
                        } else {
                            //去设置支付密码
                            SetPayPassword();
                        }
                    }
                }
                break;
            case R.id.ed_rertention_peice:
                rely_grid.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_offline_btn:
                if (TextUtils.isEmpty(price)) {
                    ToastUtils.showShort("请选择金额");
                }else {
                    if (isRead==0) {
                        ToastUtils.showShort("请先阅读车位保留金协议");
                    }else {
                        payDingJin(4, "");
                    }
                }
                break;
            default:
                break;
        }
    }
    /**
     * 获取贡献值  收益值
     */
    private void getPersonInfo() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetUserInfoById");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            // 添加到请求队列
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<JSONObject>(this, false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    JSONObject object = obj.getJSONObject("data");
                                    //收益值
                                    share_num.setText("(剩余"+object.getString("incomevalue")+""+"收益值)");
                                } else {

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }
    public void payDingJin(final int type, String payPassword) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "UserPayAdvanceMoney");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("advanceMoney", price);
            mRequest.add("type",type);
            mRequest.add("spaceId",buyBean.getSpaceId());
            mRequest.add("isByStage",buyBean.getIsByStage());
            mRequest.add("username",buyBean.getUsername());
            mRequest.add("userPhone",buyBean.getUserPhone());
            mRequest.add("dealUserName",ed_pricename.getText().toString());
            mRequest.add("dealPhone",ed_pricephone.getText().toString());
            if(type == 1) {
                mRequest.add("appId",LrConstant.WX_APP_ID);
            } else {
                mRequest.add("payPassword",payPassword);
            }
            if(buyBean.getIsByStage() == 1) {
                mRequest.add("stageNumber",buyBean.getStageNumber());
                mRequest.add("firstPay",buyBean.getFirstPay());
                mRequest.add("eachStagePrice",buyBean.getEachStagePrice());
                mRequest.add("bankId",buyBean.getBankId());
            }

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<WxM>(baseContext, true, WxM.class) {
                        @Override
                        public void doWork(WxM data, String code) {
                            if (code.equals("1")) {
                                if (type == 1){
                                    AppConfig.getInstance().putString("wx_order_id", data.getData().getOrderNo());
                                    Params.PAY_FROM_TAG = 2;
                                    doWXPay(data.getData());
                                }else if (type==2){
                                    //跳转到成功的界面可查看可查看详情
                                    startActivity(new Intent(RetentionMoneyActivity.this, ReserveSucceedActivity.class)
                                            .putExtra("orderno", data.getData().getOrderNo())
                                    );
                                }else if (type==4){
                                    startActivity(SubmitSuccessActivity.class);
                                    finish();
                                }
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    /**
     * 微信支付
     * @param data
     */
    private void doWXPay(WxM.Data data) {
        PayReq request = new PayReq();
        request.appId = LrConstant.WX_APP_ID;
        request.partnerId = data.getPartnerid();
        request.prepayId= data.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr= data.getNoncestr();
        request.timeStamp= data.getTimestamp();
        request.sign= data.getSign();
        request.extData = "app data";
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShort("微信支付获取中....");
            }
        });
        boolean isPaySupported = Application.mWxApi.isWXAppInstalled();
        if(!isPaySupported){
            ToastUtils.showShort("手机不支持微信支付");
            return;
        }
        Application.mWxApi.sendReq(request);
    }

    /**
     * 实名认证的判断
     * @return
     */
    public boolean isAuth () {
        CarCommon carCommon = new CarCommon();
        if (hasRealAuth.equals("0")) {
            carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                @Override
                public void setSure() {
                    startActivity(ApproveActivity.class);
                }
            });
            carCommon.CommonDialog(RetentionMoneyActivity.this,"请您先去进行实名认证",null);
            return false;
        }else if (hasRealAuth.equals("2")){
            carCommon.ReminderDialog(RetentionMoneyActivity.this,"身份信息正在审核中，请稍候再试",null);
            return false;
        } else if (hasRealAuth.equals("3")) {
            carCommon.ReminderDialog(RetentionMoneyActivity.this,"您的实名认证未通过，请重新在个人中心认证",null);
            return false;
        } else {
            return true;
        }
    }
    /**
     * 支付弹框
     */
    public void showPayDialog() {
        paydialog = new AlertDialog.Builder(this).create();
        paydialog.setCanceledOnTouchOutside(false);
        paydialog.setView(new EditText(this));
        paydialog.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(editSecurityCode!=null){
                    //设置可获得焦点
                    editSecurityCode.getEditText().setFocusable(true);
                    editSecurityCode.getEditText().setFocusableInTouchMode(true);
                    //请求获得焦点
                    editSecurityCode.getEditText().requestFocus();
                    //调用系统输入法
                    InputMethodManager inputManager = (InputMethodManager) editSecurityCode.getEditText()
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSecurityCode.getEditText(), 0);
                }
            }
        }, 200);
        Window window = paydialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        paydialog.setContentView(R.layout.activity_input_password_dialog);
        final RelativeLayout pay_back=(RelativeLayout)window.findViewById(R.id.pay_back);
        pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paydialog.dismiss();
            }
        });
        editSecurityCode = (SecurityPasswordEditText) window
                .findViewById(R.id.security_linear);
        editSecurityCode.setSecurityEditCompileListener(new SecurityEditCompileListener() {
            @Override
            public void onNumCompleted(String num) {
                // TODO: 2017/12/1  支付接口
                paydialog.dismiss();
               payDingJin(2,num);
            }
        });
    }
    /**
     * 这个是判断是不是已经设置支付密码
     */
    private void SetPayPassword(){
        final NormalDialog dialog = new NormalDialog(baseContext);
        dialog.title("安全提示")
                .titleTextColor(baseContext.getResources().getColor(R.color.black_color))
                .titleTextSize(15)
                .content("您还没有支付密码，请先设置！")
                .contentTextSize(15)
                .contentTextColor(baseContext.getResources().getColor(R.color.gray_color))
                .btnText("取消", "设置")
                .btnNum(2)
                .style(NormalDialog.STYLE_TWO)
                .btnTextColor(baseContext.getResources().getColor(R.color.gray_color), baseContext.getResources().getColor(R.color.colorAccent))
                .btnTextSize(15, 15)
                .widthScale(0.8f)//
                .showAnim(new BounceTopEnter())//
                .dismissAnim(new SlideBottomExit())//
                .cornerRadius(7)
                .show();
        dialog.setCancelable(true);
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        startActivity(SetPayPasswordActivity.class);
                    }
                });
    }
    //brck 返回提示
    private void setBackMessage(){
        CarCommon carCommon = new CarCommon();
        carCommon.CommonDialog(this,"此车位将被其他用户订购，如您现在交定金，车位将为您保留，定金7日内可退款","确定不交定金吗？");
        carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
            @Override
            public void setSure() {
                EventBus.getDefault().post(new IsStallPayEvent());
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        setBackMessage();
    }
}
